package com.uduemc.biso.node.web.api.controller.noauthentication;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.core.utils.FileContentType;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.api.service.WatermarkService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@RequestMapping("/api/image")
@Controller
public class ApiImageController {

    @Autowired
    private RepertoryService repertoryServiceImpl;

    @Autowired
    private WatermarkService watermarkServiceImpl;

    @Autowired
    private GlobalProperties globalProperties;

    @Autowired
    private HostService hostServiceImpl;

    @GetMapping("/repertory/{hostsecret}/{secret}")
    public void repertoryImage(@PathVariable("hostsecret") String hostsecret, @PathVariable("secret") String secret, HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        secret = secret.substring(0, secret.lastIndexOf("."));
        String de = CryptoJava.de(secret);
        String hostDe = CryptoJava.de(hostsecret);
        int id = 0;
        int hostId = 0;
        if (de != null) {
            try {
                hostId = Integer.valueOf(hostDe);
                id = Integer.valueOf(de);
            } catch (NumberFormatException e) {
            }
        }
        if (id < 1 || hostId < 1) {
            throw new NotFoundException("repertoryImage 未能获取到id以及hostId数据！");
        }
        HRepertory hRepertory = repertoryServiceImpl.getInfoByid(id);
        if (hRepertory == null || hRepertory.getType().shortValue() != 0 || hRepertory.getHostId().longValue() != hostId) {
            throw new NotFoundException("repertoryImage 未能获取到hRepertory数据！");
        }

        String uri = request.getRequestURI();
        String substring = uri.substring(uri.lastIndexOf(".") + 1);
        if (!substring.equals(hRepertory.getSuffix())) {
            throw new NotFoundException("repertoryImage 获取到hRepertory数据与实际中的后缀不符！");
        }

        String basePath = globalProperties.getSite().getBasePath();

        Host host = hostServiceImpl.getInfoById(hRepertory.getHostId());

        // 通过 basePath 以及 code 获取 用户的目录
        String userPathByCode = SitePathUtil.getUserPathByCode(basePath, host.getRandomCode());
        String filepath = hRepertory.getFilepath();
        String filefullpath = userPathByCode + "/" + filepath;

        // 返回图片
        File file = new File(filefullpath);// 得到文件

        String contentType = FileContentType.contentType(file);

        // 是否存在
        if (!file.isFile()) {
            throw new NotFoundException("repertoryImage 获取到hRepertory数据，实际图片文件地址不存在！filefullpath：" + filefullpath);
        }
        FileInputStream fis;
        fis = new FileInputStream(file);

        long size = file.length();
        byte[] temp = new byte[(int) size];
        fis.read(temp, 0, (int) size);
        fis.close();
        byte[] data = temp;
        OutputStream out = response.getOutputStream();
        response.setContentType(StrUtil.isNotBlank(contentType) ? contentType : ("image/" + hRepertory.getSuffix()));
        out.write(data);

        out.flush();
        out.close();
        return;
    }

    @GetMapping("/watermark/{hostsecret}/watermark_*")
    public void watermarkImage(@PathVariable("hostsecret") String hostsecret, HttpServletResponse response) {
        String[] makeTestWatermarkName = watermarkServiceImpl.makeTestWatermarkName();
        String watermarkFilename = makeTestWatermarkName[1];
        File file = new File(watermarkServiceImpl.makeWatermarkFilepath(watermarkFilename));
        if (file.isFile()) {
            String contentType = null;
            FileInputStream openInputStream = null;
            try {
                contentType = new MimetypesFileTypeMap().getContentType(file);
                openInputStream = FileUtils.openInputStream(file);

                if (openInputStream != null) {
                    long size = file.length();
                    response.setHeader("Accept-Ranges", "bytes");
                    response.setHeader("Content-Length", "" + size);
                    byte[] temp = new byte[(int) size];
                    openInputStream.read(temp, 0, (int) size);
                    openInputStream.close();
                    byte[] data = temp;
                    OutputStream out = response.getOutputStream();
                    response.setCharacterEncoding("utf-8");
                    response.setContentType(contentType);
                    out.write(data);

                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (openInputStream != null) {
                    try {
                        openInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    @GetMapping("/watermark/{hostsecret}/test_watermark_*")
    public void testWatermarkImage(@PathVariable("hostsecret") String hostsecret, HttpServletResponse response)
            throws JsonParseException, JsonMappingException, JsonProcessingException, IOException, Exception {
        watermarkServiceImpl.testFontImage(2, response);
    }

}
